/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package olympicgamesgui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Collections;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import olympicgameslogic.*;

/**
 *
 * @author Fabio Mendonca
 */
public class DialogDelegMain extends JFrame {

   private JPanel pNorte, pMod, pMbt, pCentro;
   private JScrollPane painel1;
   private JLabel nome;
   private JTable tabela1;
   private JButton MBt1, MBt2, MBt3, MBt4;
   private static int linha;
   private ClassLoader cldr = this.getClass().getClassLoader();
/// variaveis para a tabela subsituir por dados recebidos em array
   String[] columnNames = {"Flag", "Country", "ICO Code", "Edition Medals", "Total Medals"};
   private Delegation deleg_temp;
   private DefaultTableModel TableModel;
   private JComboBox combobox1;

   public DialogDelegMain(String titulo) {
      super(titulo);
      super.setIconImage(Toolkit.getDefaultToolkit().getImage(cldr.getResource("images/extra/icon.png")));
      setLayout(new BorderLayout());
      pNorte = new JPanel(new BorderLayout());
      pNorte.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
      nome = new JLabel();
      nome.setText("Delegations");
      nome.setFont(new Font("Arial", Font.PLAIN + Font.BOLD, 20));
      ImageIcon img = new ImageIcon(cldr.getResource("images/extra/database.png"));
      nome.setIcon(img);
      pNorte.add(nome, BorderLayout.CENTER);
      pNorte.setBackground(Color.WHITE);

      JPanel select = new JPanel(new FlowLayout(FlowLayout.LEFT));
      JLabel edic = new JLabel("Edition");
      edic.setOpaque(false);
      select.setBackground(Color.white);
      select.setOpaque(false);
      LinkedList<Edition> editions = OlympicGamesGui.ap.getEditions();
      combobox1 = new JComboBox(editions.toArray());


      combobox1.addActionListener(new ActionListener() {

	 @Override
	 public void actionPerformed(ActionEvent e) {
	    JComboBox box = (JComboBox) (e.getSource());
	    if (box.getSelectedIndex() > -1) {
	       refreshTable();
	    }
	 }
      });




      System.out.println("" + (String) OlympicGamesGui.ap.getEditions().toString());
      select.add(edic);
      select.add(combobox1);
      pNorte.add(select, BorderLayout.WEST);
      add(pNorte, BorderLayout.NORTH);

//barra com botões
      pMod = new JPanel(new BorderLayout());
      pMbt = new JPanel(new FlowLayout());
      MBt1 = new JButton("New", new ImageIcon(cldr.getResource("images/extra/database_add.png")));
      MBt3 = new JButton("Delete", new ImageIcon(cldr.getResource("images/extra/database_delete.png")));
      MBt4 = new JButton("Manage", new ImageIcon(cldr.getResource("images/extra/users.png")));
      pMbt.add(MBt1);
      pMbt.add(MBt3);
      pMbt.add(MBt4);

//criar tabela atraves do arraylist           

      //Tabela fazer codigo para carregad dados relativos a um determinado país.   

      tabela1 = new JTable() {

	 public boolean isCellEditable(int rowIndex, int colIndex) {
	    return false; //Disallow the editing of any cell
	 }

	 public Class getColumnClass(int column) {
	    if (column == 0) {
	       return ImageIcon.class;
	    }
	    return Object.class;
	    //return getValueAt(0, column).getClass();
	 }
      };
      TableModel = (DefaultTableModel) tabela1.getModel();
      TableModel.setColumnIdentifiers(columnNames);
      setUpTableData();

      JTableHeader header = tabela1.getTableHeader();
      header.setBackground(Color.DARK_GRAY);
      header.setFont(new Font("Arial", Font.BOLD, 12));
      header.setForeground(Color.WHITE);
      tabela1.setPreferredScrollableViewportSize(new Dimension(300, 70));
      tabela1.setFillsViewportHeight(true);
      tabela1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      tabela1.getSelectionModel().addListSelectionListener(new DialogDelegMain.RowListener3());
      tabela1.getTableHeader().setReorderingAllowed(false);




//construir painel para tab de atletas  
      pMod.add(pMbt, BorderLayout.NORTH);
      painel1 = new JScrollPane(tabela1);
      pMod.add(painel1, BorderLayout.CENTER);
      pCentro = new JPanel(new BorderLayout());
      pCentro.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
      pCentro.add(pMbt, BorderLayout.NORTH);
      pCentro.add(pMod, BorderLayout.CENTER);
      add(pCentro, BorderLayout.CENTER);


      setMinimumSize(new Dimension(450, 400));
      setSize(450, 400);
      setVisible(true);
      setDefaultCloseOperation(DISPOSE_ON_CLOSE);
      setLocationRelativeTo(null);


      addWindowListener(new WindowAdapter() {

	 @Override
	 public void windowClosing(WindowEvent e) {
	    dispose();
	 }
      });
//        Eventos dos botoões
      //Botão Criar novo        
      MBt1.addActionListener(new ActionListener() {

	 @Override
	 public void actionPerformed(ActionEvent e) {
	    if (OlympicGamesGui.ap.getEditions().size() > 0) {
	       LinkedList<Nation> list = OlympicGamesGui.ap.getNations();
	       if (list.size() > 0) {
		  Edition n = (Edition) combobox1.getSelectedItem();
		  int ano = n.getYear();
		  Edition ed = OlympicGamesGui.ap.getEdition(ano);

		  for (Delegation del : ed.getEditionDelegationList()) {
		     for (Nation nat : list) {
			if (del.getCountry().equals(nat)) {
			   list.remove(nat);
			}
		     }
		  }
		  Object[] l = list.toArray();
		  ImageIcon img2 = new ImageIcon(cldr.getResource("images/extra/database.png"));
		  Nation test = (Nation) JOptionPane.showInputDialog(DialogDelegMain.this, "Create Delegation", "Delegation Add", JOptionPane.OK_OPTION, img2, l, l[0]);
		  if (test != null) {
		     OlympicGamesGui.ap.getEdition(ano).addDelegation(new Delegation(test, OlympicGamesGui.ap.getEdition(ano)));
		     refreshTable();
		  }
	       } else {
		  JOptionPane.showMessageDialog(DialogDelegMain.this, "There are no Nation data loaded in the system yet!",
			  getTitle(), JOptionPane.WARNING_MESSAGE);
		  return;

	       }

	    } else {
	       JOptionPane.showMessageDialog(DialogDelegMain.this, "There are no editions configured!",
		       getTitle(), JOptionPane.WARNING_MESSAGE);
			 return;
	    }


	 }
      });

      //Botão apagar 
      MBt3.addActionListener(new ActionListener() {

	 @Override
	 public void actionPerformed(ActionEvent e) {
	    if (combobox1.getSelectedIndex() > -1 && deleg_temp != null) {
	       Edition n = (Edition) combobox1.getSelectedItem();
	       int ano = n.getYear();
	       //if (deleg_temp != null) {
	       int i = JOptionPane.showConfirmDialog(DialogDelegMain.this, "Remove Delegation\nConfirm?", "Remove Delegation", JOptionPane.YES_NO_OPTION, JOptionPane.YES_NO_OPTION);
	       if (i == JOptionPane.YES_OPTION) {
		  OlympicGamesGui.ap.getEdition(ano).getEditionDelegationList().remove(deleg_temp);
		  refreshTable();
		  JOptionPane.showMessageDialog(DialogDelegMain.this, "User Removed");
	       }
	    } else {
	       JOptionPane.showMessageDialog(DialogDelegMain.this, "No User Selected");
	    }
	 }
      });

      MBt4.addActionListener(new ActionListener() {

	 @Override
	 public void actionPerformed(ActionEvent e) {
	    if (deleg_temp == null) {
	       JOptionPane.showMessageDialog(DialogDelegMain.this, "Please select a delegation to manage",
		       getTitle(), JOptionPane.WARNING_MESSAGE);
	    } else {
	       DialogManageDelegation jan = new DialogManageDelegation("Manage Delegation", deleg_temp);
	       deleg_temp = null;
	    }


	 }
      });

      addWindowListener(new WindowAdapter() {

	 @Override
	 public void windowClosing(WindowEvent e) {
	    dispose();
	 }
      });
   }

   private class RowListener3 implements ListSelectionListener {

      @Override
      public void valueChanged(ListSelectionEvent event) {
	 Edition n = (Edition) combobox1.getSelectedItem();
	 int ano = n.getYear();
	 if (event.getValueIsAdjusting()) {
	    return;
	 }
	 linha = tabela1.getSelectedRow();
	 if (linha == -1) {
	    linha = 0;
	 } else {
	    for (Delegation d : OlympicGamesGui.ap.getEdition(ano).getEditionDelegationList()) {
	       if (tabela1.getValueAt(linha, 1).toString().equals(d.getCountry().getName().toString())) {
		  deleg_temp = d;
	       }
	    }
	 }
      }
   }

   private void setUpTableData() {
      if (combobox1.getSelectedIndex() > -1) {
	 Edition n = (Edition) combobox1.getSelectedItem();
	 int ano = n.getYear();
	 Object[][] data1 = new Object[OlympicGamesGui.ap.getEdition(ano).getEditionDelegationList().getSize()][columnNames.length];
	 int i = 0;
	 LinkedList<Delegation> tempEd = OlympicGamesGui.ap.getEdition(ano).getEditionDelegationList();
	 Collections.sort(tempEd, new Delegation.DelegationName());
	 for (Delegation s : tempEd) {
	    ImageIcon img3 = new ImageIcon(cldr.getResource("images/flags/" + s.getCountry().getCode() + ".png"));
	    data1[i][0] = img3;
	    data1[i][1] = s.getCountry().getName().toString();
	    data1[i][2] = s.getCountry().getCode().toString();
	    data1[i][3] = s.getCountry().getTotalEditionMedals(OlympicGamesGui.ap.getEditions().getElement(combobox1.getSelectedIndex()));
	    data1[i][4] = s.getCountry().getTotalMedals();
	    TableModel.addRow(data1[i]);
	    i++;
	 }
	 tabela1.setModel(TableModel);
      }
   }

   public void refreshTable() {
      TableModel.setRowCount(0);
      tabela1.removeAll();
      setUpTableData();
   }
}